import type H from 'highlight.js'
import {CustomBytemdPlugin} from "/@/types/bytemd";

declare interface BytemdPluginHighlightOptions {
    init?(hljs: typeof H): void | Promise<void>
}

/**
 * 语法高亮
 * @param highlightOptions
 */
export default function highlightPlugin(highlightOptions: BytemdPluginHighlightOptions = {}): CustomBytemdPlugin {
    let hljs: typeof H
    return {
        process: async (element: HTMLElement) => {
            const els = element.querySelectorAll<HTMLElement>('pre>code')
            if (els.length === 0) return
            if (!hljs) {
                hljs = await import('highlight.js').then((m) => m.default)
                if (highlightOptions.init) await highlightOptions.init(hljs)
            }
            els.forEach((el) => {
                hljs.highlightElement(el)
            })
        }
    };
}